var ruleDef = {
    baseUrl: "/ruleDef",
    entity: "ruleDef",
    tableId: "ruleDefTable",
    toolbarId: "toolbar",
    unique: "id",
    order: "asc",
    code:"id",
    currentItem: {}
};

ruleDef.columns = function () {
    return [{
        field: 'selectItem',
        radio: true
    }, {
        field: 'ruleName',
        title: '标题',
        formatter:function(value, row, index){
        	return "<a href='#' name='btn_detail' style='color : green' onclick='clickCell("+JSON.stringify(row)+")'>"+value+"</a>";
        }
    }, {
        field: 'pubDept',
        title: '发布单位'
    }, {
        field: 'pubDate',
        title: '日期',
        formatter:function(value, row, index){
        	if(row.pubDate.length == 8){
                var year = row.pubDate.slice(0,4);
                var month = row.pubDate.slice(4,6);
                var date = row.pubDate.slice(6,8);
                row.pubDate = year+'-'+month+'-'+date;
            }
        	return row.pubDate;
        }
    }];
};

function clickCell(row){
    $.get(ruleDef.entity+'/detail', null, function (form) {
        layer.open({
            type: 1,
            title: '规章制度',
            content: form,
            shade: false,
            area: ['100%', '100%'],
            maxmin: false,
            yes: function (index) {
                //触发表单的提交事件
                layedit.sync(editIndex);
                $('form.layui-form').find('button[lay-filter=edit]').click();
            },
            full: function (elem) {
                var win = window.top === window.self ? window : parent.window;
                $(win).on('resize', function () {
                    var $this = $(this);
                    elem.width($this.width()).height($this.height()).css({
                        top: 0,
                        left: 0
                    });
                    elem.children('div.layui-layer-content').height($this.height() - 95);
                });
            },
            success: function (layero, index) {
                var form = layui.form;
                form.render();
                $("#ruleName").text(row.ruleName);
                $("#pubDept").text(row.pubDept);
                $("#pubDate").text(row.pubDate);
                $("#ruleDesc").html(row.ruleDesc);
            }
        });
    });
}

ruleDef.queryParams = function (params) {
	if(!params)
		return false;
    var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        limit: params.limit, //页面大小
        page: params.offset/params.limit+1, //页码
    };
    return temp;
};

ruleDef.responseHandler = function(response){
	if(response.code =='200'){
		return response.data;
	}
	return false;
};

ruleDef.init = function () {
    ruleDef.table = $('#' + ruleDef.tableId).bootstrapTable({
        url: ruleDef.baseUrl, //请求后台的URL（*）
        method: 'get', //请求方式（*）
        toolbar: '#' + ruleDef.toolbarId, //工具按钮用哪个容器
        striped: true, //是否显示行间隔色
        cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true, //是否显示分页（*）
        sortable: false, //是否启用排序
        sortOrder: ruleDef.order, //排序方式
        queryParams: ruleDef.queryParams,//传递参数（*）
        sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 10, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        strictSearch: false,
        showColumns: false, //是否显示所有的列
        showRefresh: true, //是否显示刷新按钮
        minimumCountColumns: 2, //最少允许的列数
        clickToSelect: true, //是否启用点击选中行
        uniqueId: ruleDef.unique, //每一行的唯一标识，一般为主键列
        showToggle: true, //是否显示详细视图和列表视图的切换按钮
        cardView: false, //是否显示详细视图
        detailView: false, //是否显示父子表
        columns: ruleDef.columns(),
        responseHandler:ruleDef.responseHandler,
    });
};

ruleDef.select = function (layerTips) {
    var rows = ruleDef.table.bootstrapTable('getSelections');
    if (rows.length == 1) {
        ruleDef.currentItem = rows[0];
        return true;
    } else {
        layerTips.msg("请选中一行");
        return false;
    }
};

layui.use(['form', 'layedit', 'laydate'], function () {
    ruleDef.init();
    var editIndex;
    var layerTips = layui.layer, //获取父窗口的layer对象
        layer = layui.layer, //获取当前窗口的layer对象
        form = layui.form,
        layedit = layui.layedit,
        laydate = layui.laydate;
    var addBoxIndex = -1;
    //初始化页面上面的按钮事件
    $('#btn_query').on('click', function () {
        ruleDef.table.bootstrapTable('refresh',ruleDef.queryParams());
    });

    $('#btn_add').on('click', function () {
        if (addBoxIndex !== -1)
            return;
        //本表单通过ajax加载 --以模板的形式，当然你也可以直接写在页面上读取
        $.get(ruleDef.entity + '/edit', null, function (form) {
            addBoxIndex = layer.open({
                type: 1,
                title: '规章制度',
                content: form,
                btn: ['保存', '取消'],
                shade: false,
                area: ['100%', '100%'],
                maxmin: false,
                yes: function (index) {
                    layedit.sync(editIndex);
                    //触发表单的提交事件
                    $('form.layui-form').find('button[lay-filter=edit]').click();
                },
                full: function (elem) {
                    var win = window.top === window.self ? window : parent.window;
                    $(win).on('resize', function () {
                        var $this = $(this);
                        elem.width($this.width()).height($this.height()).css({
                            top: 0,
                            left: 0
                        });
                        elem.children('div.layui-layer-content').height($this.height() - 95);
                    });
                },
                success: function (layero, index) {
                	var layers = layui.layer;
                    var form = layui.form;
                    laydate.render({
                        elem: '#date' //指定元素
                      });
                    editIndex = layedit.build('description_editor',{
                    	 tool: [  'strong' //加粗
                    	          ,'italic' //斜体
                    	          ,'underline' //下划线
                    	          ,'del' //删除线
                    	          
                    	          ,'|' //分割线
                    	          
                    	          ,'left' //左对齐
                    	          ,'center' //居中对齐
                    	          ,'right' //右对齐
                    	       ]
                    	});
                    form.render();
                    form.on('submit(edit)', function (data) {
                    	if(data.field.ruleName.length>100){
                    		layerTips.msg('标题过长');
                    		return false;
                    	}
                    	if(data.field.pubDept.length>50){
                    		layerTips.msg('发布单位名称过长');
                    		return false;
                    	}
                    	if(data.field.ruleDesc.length ==0){
                    		layerTips.msg('发布内容不能为空');
                    		return false;
                    	}
                        $.ajax({
                            url: ruleDef.baseUrl,
                            type: 'post',
                            data: JSON.stringify(data.field),
                            dataType: "json",
                            contentType: "application/json; charset=utf-8",                            beforeSend: function () {
                            	layers.load(2);
                            },
                            success: function (data) {
                            	if(data.code=='200'){
                                    layerTips.msg('保存成功');                                    
                                    layer.close(index);
                                    ruleDef.table.bootstrapTable('refresh',ruleDef.queryParams());
                            	}else{
                            		 layerTips.msg(data.message);
                            		 layer.close(index);
                            	}
                            },
                            complete: function () {
                            	layer.closeAll('loading');
                            }
                            
                        });
                        //这里可以写ajax方法提交表单
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    });
                    //console.log(layero, index);
                },
                end: function () {
                    addBoxIndex = -1;
                }
            });
        });
    });
    $('#btn_edit').on('click', function () {
        if (ruleDef.select(layerTips)) {
        	var result = ruleDef.currentItem;
            $.get(ruleDef.entity+'/edit', null, function (form) {
                layer.open({
                    type: 1,
                    title: '编辑用户',
                    content: form,
                    btn: ['保存', '取消'],
                    shade: false,
                    area: ['100%', '100%'],
                    maxmin: false,
                    yes: function (index) {
                        //触发表单的提交事件
                        layedit.sync(editIndex);
                        $('form.layui-form').find('button[lay-filter=edit]').click();
                    },
                    full: function (elem) {
                        var win = window.top === window.self ? window : parent.window;
                        $(win).on('resize', function () {
                            var $this = $(this);
                            elem.width($this.width()).height($this.height()).css({
                                top: 0,
                                left: 0
                            });
                            elem.children('div.layui-layer-content').height($this.height() - 95);
                        });
                    },
                    success: function (layero, index) {
                        var form = layui.form;
                        laydate.render({
                            elem: '#date' //指定元素
                          });
                        setFromValues(layero, result);
                        layero.find('#description_editor').val(result.ruleDesc);
                        layero.find('#dateDiv').show();
                        editIndex = layedit.build('description_editor',{
                       	 tool: [  'strong' //加粗
                       	          ,'italic' //斜体
                       	          ,'underline' //下划线
                       	          ,'del' //删除线
                       	          
                       	          ,'|' //分割线
                       	          
                       	          ,'left' //左对齐
                       	          ,'center' //居中对齐
                       	          ,'right' //右对齐
                       	       ]
                       	});
                        form.render();
                        form.on('submit(edit)', function (data) {
                        	if(data.field.ruleName.length>100){
                        		layerTips.msg('标题过长');
                        		return false;
                        	}
                        	if(data.field.pubDept.length>50){
                        		layerTips.msg('发布单位名称过长');
                        		return false;
                        	}
                        	var pubDate =''; 
                        	var  strs=data.field.pubDate.split("-"); 
                        	for (i=0;i<strs.length ;i++ ) { 
                        		pubDate+=strs[i];
                        	}
                        	data.field.pubDate = pubDate;
                            $.ajax({
                                url: ruleDef.baseUrl+"/"+result.ruleNo,
                                type: 'put',
                                data: JSON.stringify(data.field),
                                dataType: "json",
                                contentType: "application/json; charset=utf-8",
                                beforeSend: function () {
                                	layer.load(2);
                                },
                                success: function (data) {
                                	if(data.code=='200'){
                                        layerTips.msg('更新成功');
                                        layer.close(index);
                                        ruleDef.table.bootstrapTable('refresh',ruleDef.queryParams());
                                	}else{
                                		layerTips.msg(data.message);
                                		layer.close(index);
                                	}
                                },
                                complete: function () {
                                	layer.closeAll('loading');
                                }

                            });
                            //这里可以写ajax方法提交表单
                            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                        });
                    }
                });
            });
        }
    });
    $('#btn_del').on('click', function () {
        if (ruleDef.select(layerTips)) {
            var id = ruleDef.currentItem.ruleNo;
            layer.confirm('确定删除数据吗？', null, function (index) {
                $.ajax({
                    url: ruleDef.baseUrl + "/" + id,
                    type: "DELETE",
                    success: function (data) {
                        if (data.code == '200') {
                            layerTips.msg("移除成功！");
                            ruleDef.table.bootstrapTable('refresh',ruleDef.queryParams());
                        } else {
                            layerTips.msg("移除失败！");
                            ruleDef.table.bootstrapTable('refresh',ruleDef.queryParams());
                        }
                    }
                });
                layer.close(index);
            });
        }
    });
})